#include <windows.h> 
#include <stdio.h> 
#include "Utils.h"
#include <detours.h> 

#define LOGFILE "C:\\Program Files\\Xenimus2\\xenergy2.log"

bool fileExists(const char filename[])
{
	WIN32_FIND_DATA finddata;
	HANDLE handle = FindFirstFileA(filename,&finddata);
	return (handle!=INVALID_HANDLE_VALUE);
} 

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{ 
	bool bFail = 0;
	char XenergyDllLoc[MAX_PATH], XenimusDir[MAX_PATH], XenimusExeLoc[MAX_PATH], DetourDllLoc[MAX_PATH], strMessage[MAX_PATH];
	Utils::Log(LOGFILE, "--Starting Xenergy--\n");
	
	//Gets xenergy.dll location
	GetModuleFileName(0, XenergyDllLoc, MAX_PATH);
	XenergyDllLoc[strlen(XenergyDllLoc)-3] = 0;
	strcat_s(XenergyDllLoc, MAX_PATH, "dll");
	
	// Get Xenimus.exe and detoured.dll locations
	GetCurrentDirectoryA(MAX_PATH, XenimusDir);
	sprintf_s(XenimusExeLoc, MAX_PATH, "%s%s", XenimusDir, "\\Xenimus.exe"); 
//	sprintf_s(DetourDllLoc, MAX_PATH, "%s%s", XenimusDir, "\\detoured.dll");

	// Check game path variables 
	// xenergy.dll
	if(!fileExists(XenergyDllLoc)) {
		Utils::Log(LOGFILE, "Couldn't find DLL"); return 0;
	} else { 
		sprintf_s(strMessage, MAX_PATH, "Found xenergy DLL at %s\n", XenergyDllLoc);
		Utils::Log(LOGFILE, strMessage);
	};
	if(!fileExists(XenimusExeLoc)) {
		Utils::Log(LOGFILE, "Couldn't find game EXE file"); return 0;
	}else { 
		sprintf_s(strMessage, MAX_PATH, "Found xenergy EXE at %s\n", XenimusExeLoc);
		Utils::Log(LOGFILE, strMessage);
	};
/*	if(!fileExists(DetourDllLoc)) {
		Utils::Log(LOGFILE, "Couldn't find detoured DLL"); return 0;
	}
	else { 
		sprintf_s(strMessage, MAX_PATH, "Found detoured DLL at %s\n", DetourDllLoc);
		Utils::Log(LOGFILE, strMessage);
	}; */


	//////////////////////////////////// 
	// Launch The Process 
	//////////////////////////////////// 
	STARTUPINFO si = {sizeof(STARTUPINFO)}; 
	PROCESS_INFORMATION pi = {0}; 

	BOOL bResult = DetourCreateProcessWithDll(
		XenimusExeLoc,
		NULL,
		0,
		0,
		TRUE, 
		CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
		NULL,
		XenimusDir,
		&si,
		&pi,
		XenergyDllLoc,
		0);

	if( !bResult )
	{ 
		// Process Failed To Launch 
		Utils::Log(LOGFILE, "Couldn't launch the process");
		return 0; 
	} 

	return 0; 

}